package com.googlecode.authproxy.servlets;

import com.googlecode.authproxy.AuthProxySettings;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;
import java.io.IOException;

/**
 * @author Niels Bosma (niels.bosma@motorola.com)
 */
public class AdminServlet extends HttpServlet
{

   private ServletContext context;

   public void init(ServletConfig config) throws ServletException
   {
      this.context = config.getServletContext();
   }
   
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      String action = request.getParameter("action");
      if(action!=null)
      {
         if("load".equals(action))
         {
            response.setContentType("text/xml");
            AuthProxySettings.getInstance().storeToXML(response.getOutputStream(), null);
         }
         else
         if("store".equals(action))
         {
            String settingsXml = request.getParameter("settings");
            if(settingsXml!=null)
            {
               AuthProxySettings settings = AuthProxySettings.getInstance();
               settings.parse(settingsXml);
               settings.save();
               settings.updateProxy();
            }
         }
         else
         {
            throw new RuntimeException("Action \""+action+"\" not supported.");
         }
      }
      else
      {
         throw new RuntimeException("Parameter \"action\" not specified.");
      }
   }
   
}
